<?php
namespace app\controller;

use app\BaseController;

use think\facade\View;

require POD_PATH.'AppPdo.php';
require EXTEND_PATH.'httpUtil/httpUtil.php';

use pod;

class HttpResultStatus
{
   public  $fail = "0"; 
   public  $success = "1"; 
}

class App extends BaseController
{
   
   
    public function index()
    {
        // 模板输出并变量赋值
        return View::fetch('index', [
                'title' => 'App',
        ]);
    }

    public function publish()
    {
        // 模板输出并变量赋值
        return View::fetch('publish', [
                'title' => '发布App',
        ]);
    }



    protected $dbmanager;

    function __construct()
    {
        # code...

        $this->dbmanager = new pod\AppPdo( DATA_DIR."/app/app.db");
    }


    /**
     * 请求参数
     */
    public function requireData(){

        if($_SERVER['REQUEST_METHOD']=="POST"){ 
            $reqObj = $_POST;
        }else if($_SERVER['REQUEST_METHOD']=="GET"){  
            //用 _GET接收.  
            $reqObj = $_GET;
        } 
        return $reqObj;
    }

    public function app()
    {
        
        # code...
        $resultStatus = new \HttpResultStatus();
        $ret = new \JSONResponse();
        try
        {
            $appurl = "";
            //$appurl = "https://".$_SERVER["HTTP_HOST"].str_replace(get_fileName(__FILE__).".php", "", $_SERVER["REQUEST_URI"])."/data/plist/";
            $arr = $this->dbmanager->queryApps();
            foreach ($arr as $key => $value) {
    # code...
                $arri = $arr[$key];
                if ($arri['type'] == 'iOS') {
        # code...
                    $arr[$key]["plist"] = $appurl.$arri["identifier"].$arri["version"].".plist";
                }else{
                    $arr[$key]["plist"] = "";
                }
                $arr[$key]['savetime'] = date("Y-m-d H:i:s",$arri['savetime']);
            }
            $ret->data =  $arr;
            $ret->status = $resultStatus->success;

            $ret->plist = $appurl;
            $ret->q = get_fileName(__FILE__);

            echo json_encode($ret,JSON_UNESCAPED_UNICODE);
        }catch(Exception $e)
        {
            $ret->status = $resultStatus->fail;
            $ret->messages = $e->getMessage();
            echo json_encode($ret,JSON_UNESCAPED_UNICODE);
        }
    }

    public function delete(){
        $req = $this->requireData();
        $arr = $this->dbmanager->queryApp($req["id"]);

        foreach ($arr as $key => $value) {
            $arri = $arr[$key];
            deldir($arri["appurl"]);
        }
        $this->dbmanager->delete($req["id"]);
        return json_encode($req,JSON_UNESCAPED_UNICODE);
    }

    public function apk(){
        $req = $this->requireData();
        $fileKey = $req["key"];
        $filePath = "";
        //"upload/Android/"
        $strArr = explode('.', $fileKey);
        $fileSubName = strtolower(end($strArr));

        if (strcmp($fileSubName,"ipa" )==0) {
            //相等
            $filePath = "upload/iOS/$fileKey";
        }else if (strcmp($fileSubName,"apk" )==0){
            $filePath = "upload/Android/$fileKey";
        }else{
            $filePath = "upload/other/$fileKey";
        }

        if (!file_exists($filePath)) {
            echo "文件不存在$filePath";
        }else{
            //这里是下载zip文件 
            header("Content-Type: application/zip");
            header("Content-Transfer-Encoding: Binary");

            header("Content-Length: " . filesize($filePath));
            header("Content-Disposition: attachment; filename=\"" . basename($filePath) . "\"");

            readfile($filePath);
        }
    }


    public function saveFile($file,$fileTmpName,$fileName,$filesize,$filetype,$appType,$filePath){
        $data["name"] = $fileName;
        $data["type"] = $filetype;
        $data["size"] = ($filesize / 1024 /1024);
        $data["tmpName"] = $fileTmpName;
        #$data["phpfile"] = __FILE__;
        $ret = new \JSONResponse();
        $resultStatus = new \HttpResultStatus();
        $ret->data = $data;
        $ret->messages ="";
        $ret->status = $resultStatus->fail;
        if ($file["error"] > 0)
        {
            $ret->messages = "error: " . $file["error"] ;
            $ret->status = $resultStatus->fail;
            switch($file["error"]) {  
                case 1:    
        // 文件大小超出了服务器的空间大小    
                $ret->messages = "The file is too large (server).";    
                break;   
                case 2:    
        // 要上传的文件大小超出浏览器限制    
                $ret->messages = "The file is too large (form).";    
                break;    

                case 3:    
        // 文件仅部分被上传    
                $ret->messages = "The file was only partially uploaded.";    
                break;    

                case 4:    
        // 没有找到要上传的文件    
                $ret->messages = "No file was uploaded.";    
                break;    

                case 5:    
        // 服务器临时文件夹丢失    
                $ret->messages = "The servers temporary folder is missing.";    
                break;    

                case 6:    
        // 文件写入到临时文件夹出错    
                $ret->messages = "Failed to write to the temporary folder.";    
                break;    
            }
        }
        else
        {
            $sucess = move_uploaded_file($fileTmpName, UPLOAD_PATH."/$appType/" . $fileName);
            if ($sucess) {
                $ret->messages = "保存成功: " . "upload/" . $fileName;
                $ret->status = $resultStatus->success;
            }else{
                $ret->messages .= 
                $fileTmpName."保存失败(fail save)";
                $ret->status = $resultStatus->fail;
            }
        //}
        }

        $logfile = fopen(DATA_DIR."/app/upload.txt", "a") or die("Unable to open file!");
        $logMsg = date("Y-m-d h:i:s").','.json_encode($ret->data)."\r\n";
        fwrite($logfile, $logMsg);
        fclose($logfile);
        return $ret;
    }

    public function upload(){

        define('ROOT',dirname(__FILE__).'/'); 

        $resultStatus = new \HttpResultStatus();

        $reqObj = $_POST;
        $file  = $_FILES["file"];
        $fileName = $file["name"];
        $filetype = $file["type"];
        $filesize = $file["size"];
        $fileTmpName = $file["tmp_name"];
//unix时间戳
        $time = time();
//转成时间格式
        date_default_timezone_set('PRC');
        $dadte = date('Ymd',$time);
        $strArr = explode('.', $fileName);

        $version = date('Ymdhis',$time);

        $fileSubName = strtolower(end($strArr));
        $fileName =  $dadte.'_'.$strArr[0]."$version.".$fileSubName;

        $appType = "";
        if (strcmp($fileSubName,"ipa" )==0) {
            //相等
            $appType = "iOS";
        }else if (strcmp($fileSubName,"apk" )==0){
            $appType = "Android";
        }else{
            echo "<script type='text/javascript'>alert('文件类型不对".$fileSubName ."');</script>";
            exit();
        }
        $filePath = UPLOAD_PATH."/$appType/" . $fileName;

        $ret = $this->saveFile($file,$fileTmpName,$fileName,$filesize,$filetype,$appType,$filePath);
        echo "<script type='text/javascript'>alert('".$ret->messages."');</script>";
        if ($ret->status == $resultStatus->fail) {
            exit();
        }
        require_once EXTEND_PATH."/PCLZip/pclzip.lib.php";
    //这里需要注意该目录是否存在，并且有创建的权限
        $zipname = $filePath;
        $archive = new \PclZip($zipname);
    //$v_list = $archive->listContent();

        $uzipPath = TMP_PATH."/$fileName.tmp";

        if ($appType == "iOS") {
            if ($archive->extract(PCLZIP_OPT_PATH, $uzipPath)){ //data换成其他路径即可
        //die("Error : ".$archive->errorInfo(true));
            } try {

            } catch (Exception $e) {
                echo "$e";
            }

            require_once EXTEND_PATH.'/CFPropertyList/classes/CFPropertyList/CFPropertyList.php';

            $forgname =  str_replace(".ipa", "", $file["name"]);
            $content = file_get_contents("$uzipPath/Payload/$forgname.app/Info.plist");
            $plist = new CFPropertyList\CFPropertyList();
            $plist->parse($content);


            $arr = $plist->toArray();

            $version = $arr["CFBundleShortVersionString"];

            $identifier =  $arr["CFBundleIdentifier"];

            if (isset($arr["name"])) {
                $name = $arr["name"];
            }else{
                $name = isset($arr["CFBundleDisplayName"])?$arr["CFBundleDisplayName"]:$arr["CFBundleName"];
            }

            require_once 'driver/Sqlite.php';
            $fileNameOld = $fileName;
            $fileName =  $dadte.'_'.$strArr[0]."$version.".end($strArr);
            $filePath = UPLOAD_PATH."/$appType/" . $fileName;
            $sucess = move_uploaded_file($fileNameOld,$filePath);

            $dbmanager = new DBManager("data/data.db");
            $dbmanager->save($appType,$name,$identifier,$version,$filePath,"",$reqObj["description"]);


            require_once "plist.php";

            $plistManager = new PlistFileManager();



            $appurl = $_SERVER["REQUEST_SCHEME"]."://".$_SERVER["HTTP_HOST"].str_replace(get_fileName(__FILE__).".php", "", $_SERVER["REQUEST_URI"]);
            $plistManager->create($name,$identifier,$appurl,"",$version);
        }else{
            require_once 'driver/Sqlite.php';
            require_once 'apkp/apkParser.php';
            $apkp = new ApkParser($filePath);
            $apkDetail = $apkp->getApkDetail();
//echo '<img src="./icon/'.$apkDetail['icon'].'">';
//echo '<br />';
//echo '<pre>';
//var_dump($apkDetail);
//echo '</pre>';
            $fileNameOld = $fileName;
            $fileName =  $dadte.'_'.$strArr[0]."$version.".end($strArr);
            $filePath = "upload/$appType/" . $fileName;
            $sucess = move_uploaded_file($fileNameOld,$filePath);


            $dbmanager = new DBManager("data/data.db");
            $dbmanager->save($appType,$apkDetail["appName"],$apkDetail["package"],$apkDetail["versionName"],$filePath,"",$reqObj["description"]);

            $uzipPath = $apkp->getUnZipDir();
        }
        deldir($uzipPath);
    }

}
